<template>
  <div class="material-management">
    <!-- 顶部搜索栏和系统管理入口 -->
    <div class="header-section">
      <a-row :gutter="16" align="middle">
        <a-col :span="12">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索物料信息..."
            style="width: 300px"
            @search="handleSearch"
          />
        </a-col>
        <a-col :span="12" style="text-align: right">
          <a-space>
            <a-button type="text" @click="openSystemSettings">
              <template #icon><SettingOutlined /></template>
              系统管理
            </a-button>
            <a-dropdown>
              <a-button type="text">
                <template #icon><UserOutlined /></template>
                {{ currentUser?.name || '用户' }}
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="profile" @click="handleProfile">
                    个人资料
                  </a-menu-item>
                  <a-menu-item key="settings" @click="handleSettings">
                    设置
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="logout" @click="handleLogout">
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 物料信息表单 -->
    <a-card title="物料信息" class="material-form-card">
      <a-form
        ref="formRef"
        :model="materialForm"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="企业编码" name="enterpriseCode">
              <a-input v-model:value="materialForm.enterpriseCode" placeholder="请输入企业编码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料名称" name="materialName">
              <a-input v-model:value="materialForm.materialName" placeholder="请输入物料名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="型号" name="model">
              <a-input v-model:value="materialForm.model" placeholder="请输入型号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料分类" name="category">
              <a-select v-model:value="materialForm.category" placeholder="请选择物料分类">
                <a-select-option value="electronics">电子元件</a-select-option>
                <a-select-option value="mechanical">机械零件</a-select-option>
                <a-select-option value="raw">原材料</a-select-option>
                <a-select-option value="packaging">包装材料</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="品牌" name="brand">
              <a-input v-model:value="materialForm.brand" placeholder="请输入品牌" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="基础单位" name="baseUnit">
              <a-input v-model:value="materialForm.baseUnit" placeholder="请输入基础单位" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 包装方式选择 -->
    <a-card title="包装方式" class="packaging-card">
      <a-form-item label="包装方式" name="packagingType">
        <a-select v-model:value="materialForm.packagingType" placeholder="请选择包装方式">
          <a-select-option value="box">盒装</a-select-option>
          <a-select-option value="bag">袋装</a-select-option>
          <a-select-option value="bottle">瓶装</a-select-option>
          <a-select-option value="bulk">散装</a-select-option>
        </a-select>
      </a-form-item>

      <!-- 包装方式详细信息表格 -->
      <a-divider orientation="left">包装详细信息</a-divider>
      <a-table
        :columns="packagingColumns"
        :data-source="materialForm.packagingDetails"
        :pagination="false"
        bordered
      >
        <template #bodyCell="{ column, index }">
          <template v-if="column.key === 'operation'">
            <a-space>
              <a-button type="link" size="small" @click="editPackagingDetail(index)">
                编辑
              </a-button>
              <a-button type="link" size="small" danger @click="removePackagingDetail(index)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
      <a-button type="dashed" style="width: 100%; margin-top: 16px" @click="addPackagingDetail">
        <PlusOutlined />
        添加包装详情
      </a-button>
    </a-card>

    <!-- 物料参数表格 -->
    <a-card title="物料参数" class="parameters-card">
      <a-table
        :columns="parameterColumns"
        :data-source="materialForm.parameters"
        :pagination="false"
        bordered
      >
        <template #bodyCell="{ column, index }">
          <template v-if="column.key === 'operation'">
            <a-space>
              <a-button type="link" size="small" @click="editParameter(index)">
                编辑
              </a-button>
              <a-button type="link" size="small" danger @click="removeParameter(index)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
      <a-button type="dashed" style="width: 100%; margin-top: 16px" @click="addParameter">
        <PlusOutlined />
        添加参数
      </a-button>
    </a-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <a-space>
        <a-button type="primary" size="large" @click="handleSave">
          保存
        </a-button>
        <a-button size="large" @click="handleCancel">
          取消
        </a-button>
      </a-space>
    </div>

    <!-- 包装详情编辑模态框 -->
    <a-modal
      v-model:open="packagingModalVisible"
      title="编辑包装详情"
      @ok="savePackagingDetail"
      @cancel="cancelPackagingDetail"
    >
      <a-form :model="currentPackagingDetail" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="序号">
          <a-input-number v-model:value="currentPackagingDetail.sequence" style="width: 100%" />
        </a-form-item>
        <a-form-item label="换算数量">
          <a-input-number v-model:value="currentPackagingDetail.conversionQuantity" style="width: 100%" />
        </a-form-item>
        <a-form-item label="单位">
          <a-input v-model:value="currentPackagingDetail.unit" placeholder="请输入单位" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="currentPackagingDetail.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 参数编辑模态框 -->
    <a-modal
      v-model:open="parameterModalVisible"
      title="编辑参数"
      @ok="saveParameter"
      @cancel="cancelParameter"
    >
      <a-form :model="currentParameter" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="序号">
          <a-input-number v-model:value="currentParameter.sequence" style="width: 100%" />
        </a-form-item>
        <a-form-item label="参数名称">
          <a-input v-model:value="currentParameter.name" placeholder="请输入参数名称" />
        </a-form-item>
        <a-form-item label="参数值">
          <a-input v-model:value="currentParameter.value" placeholder="请输入参数值" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="currentParameter.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { SettingOutlined, UserOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'ant-design-vue'

interface MaterialForm {
  enterpriseCode: string
  materialName: string
  model: string
  category: string
  brand: string
  baseUnit: string
  packagingType: string
  packagingDetails: PackagingDetail[]
  parameters: MaterialParameter[]
}

interface PackagingDetail {
  key: string
  sequence: number
  conversionQuantity: number
  unit: string
  remark: string
}

interface MaterialParameter {
  key: string
  sequence: number
  name: string
  value: string
  remark: string
}

const router = useRouter()
const formRef = ref<FormInstance>()
const searchText = ref('')

// 当前用户信息
const currentUser = computed(() => {
  // 从store获取用户信息
  return {
    name: '管理员',
    email: 'admin@example.com'
  }
})

// 物料表单数据
const materialForm = reactive<MaterialForm>({
  enterpriseCode: '',
  materialName: '',
  model: '',
  category: '',
  brand: '',
  baseUnit: '',
  packagingType: 'box',
  packagingDetails: [],
  parameters: []
})

// 表单验证规则
const formRules = {
  enterpriseCode: [{ required: true, message: '请输入企业编码', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
  baseUnit: [{ required: true, message: '请输入基础单位', trigger: 'blur' }]
}

// 包装详情表格列配置
const packagingColumns = [
  {
    title: '序号',
    dataIndex: 'sequence',
    key: 'sequence',
    width: 80
  },
  {
    title: '换算数量',
    dataIndex: 'conversionQuantity',
    key: 'conversionQuantity',
    width: 100
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 100
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark'
  },
  {
    title: '操作',
    key: 'operation',
    width: 120
  }
]

// 参数表格列配置
const parameterColumns = [
  {
    title: '序号',
    dataIndex: 'sequence',
    key: 'sequence',
    width: 80
  },
  {
    title: '参数名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '参数值',
    dataIndex: 'value',
    key: 'value',
    width: 150
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark'
  },
  {
    title: '操作',
    key: 'operation',
    width: 120
  }
]

// 包装详情模态框相关
const packagingModalVisible = ref(false)
const currentPackagingIndex = ref(-1)
const currentPackagingDetail = reactive<PackagingDetail>({
  key: '',
  sequence: 0,
  conversionQuantity: 1,
  unit: '',
  remark: ''
})

// 参数模态框相关
const parameterModalVisible = ref(false)
const currentParameterIndex = ref(-1)
const currentParameter = reactive<MaterialParameter>({
  key: '',
  sequence: 0,
  name: '',
  value: '',
  remark: ''
})

// 搜索功能
const handleSearch = (value: string) => {
  console.log('搜索:', value)
  message.info(`搜索: ${value}`)
}

// 顶部工具栏功能
const openSystemSettings = () => {
  message.info('打开系统管理')
}

const handleProfile = () => {
  message.info('打开个人资料')
}

const handleSettings = () => {
  message.info('打开设置')
}

const handleLogout = () => {
  message.success('退出登录成功')
  router.push('/login')
}

// 包装详情表格操作
const addPackagingDetail = () => {
  currentPackagingIndex.value = -1
  Object.assign(currentPackagingDetail, {
    key: Date.now().toString(),
    sequence: materialForm.packagingDetails.length + 1,
    conversionQuantity: 1,
    unit: '',
    remark: ''
  })
  packagingModalVisible.value = true
}

const editPackagingDetail = (index: number) => {
  currentPackagingIndex.value = index
  Object.assign(currentPackagingDetail, materialForm.packagingDetails[index])
  packagingModalVisible.value = true
}

const removePackagingDetail = (index: number) => {
  materialForm.packagingDetails.splice(index, 1)
}

const savePackagingDetail = () => {
  if (currentPackagingIndex.value >= 0) {
    // 编辑现有记录
    materialForm.packagingDetails[currentPackagingIndex.value] = { ...currentPackagingDetail }
  } else {
    // 添加新记录
    materialForm.packagingDetails.push({ ...currentPackagingDetail })
  }
  packagingModalVisible.value = false
}

const cancelPackagingDetail = () => {
  packagingModalVisible.value = false
}

// 参数表格操作
const addParameter = () => {
  currentParameterIndex.value = -1
  Object.assign(currentParameter, {
    key: Date.now().toString(),
    sequence: materialForm.parameters.length + 1,
    name: '',
    value: '',
    remark: ''
  })
  parameterModalVisible.value = true
}

const editParameter = (index: number) => {
  currentParameterIndex.value = index
  Object.assign(currentParameter, materialForm.parameters[index])
  parameterModalVisible.value = true
}

const removeParameter = (index: number) => {
  materialForm.parameters.splice(index, 1)
}

const saveParameter = () => {
  if (currentParameterIndex.value >= 0) {
    // 编辑现有记录
    materialForm.parameters[currentParameterIndex.value] = { ...currentParameter }
  } else {
    // 添加新记录
    materialForm.parameters.push({ ...currentParameter })
  }
  parameterModalVisible.value = false
}

const cancelParameter = () => {
  parameterModalVisible.value = false
}

// 保存和取消操作
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    console.log('保存物料信息:', materialForm)
    message.success('保存成功')
    router.push('/admin/material')
  } catch (error) {
    message.error('请检查表单填写是否正确')
  }
}

const handleCancel = () => {
  router.push('/admin/material')
}
</script>

<style scoped lang="scss">
.material-management {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;

  .header-section {
    background: white;
    padding: 16px 24px;
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .material-form-card,
  .packaging-card,
  .parameters-card {
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .action-buttons {
    text-align: center;
    margin-top: 32px;
  }

  :deep(.ant-card-head) {
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 600;
  }
}
</style>